<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Python Docker FastAPI快速开发部署RESTful API - (power up)</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="Kevin Jiang" /><meta name="description" content="本文介绍如何快速使用Python, Docker, FastAPI快速开发RESTful API，以及如何编译为Docker镜像，使用Docker容器运行程序" /><meta name="keywords" content="KevinJiang, AI大模型, AI落地, 全栈工程师, Java, Spring Boot" />






<meta name="generator" content="Hugo 0.84.4 with theme even" />


<link rel="canonical" href="http://kevinjiang.info/post/python/python&#43;docker&#43;fastapi%E5%BF%AB%E9%80%9F%E5%BC%80%E5%8F%91%E9%83%A8%E7%BD%B2restful-api/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.78f8f17bab244b9ee62ad16480c9584d5fc2db06ae20681d1ca225cefd80767c.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="Python Docker FastAPI快速开发部署RESTful API" />
<meta property="og:description" content="本文介绍如何快速使用Python, Docker, FastAPI快速开发RESTful API，以及如何编译为Docker镜像，使用Docker容器运行程序" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://kevinjiang.info/post/python/python&#43;docker&#43;fastapi%E5%BF%AB%E9%80%9F%E5%BC%80%E5%8F%91%E9%83%A8%E7%BD%B2restful-api/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2023-06-06T19:32:18+08:00" />
<meta property="article:modified_time" content="2023-06-06T19:32:18+08:00" />

<meta itemprop="name" content="Python Docker FastAPI快速开发部署RESTful API">
<meta itemprop="description" content="本文介绍如何快速使用Python, Docker, FastAPI快速开发RESTful API，以及如何编译为Docker镜像，使用Docker容器运行程序"><meta itemprop="datePublished" content="2023-06-06T19:32:18+08:00" />
<meta itemprop="dateModified" content="2023-06-06T19:32:18+08:00" />
<meta itemprop="wordCount" content="1957">
<meta itemprop="keywords" content="Python,FastAPI,Docker," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Python Docker FastAPI快速开发部署RESTful API"/>
<meta name="twitter:description" content="本文介绍如何快速使用Python, Docker, FastAPI快速开发RESTful API，以及如何编译为Docker镜像，使用Docker容器运行程序"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">(Power up)</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">归档</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">标签</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">分类</li>
      </a><a href="/resume/">
        <li class="mobile-menu-item">简历</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">(Power up)</a>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">归档</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/resume/">简历</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">Python Docker FastAPI快速开发部署RESTful API</h1>

      <div class="post-meta">
        <span class="post-time"> 2023-06-06 </span>
        <div class="post-category">
            <a href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/"> 编程语言 </a>
            </div>
          <span class="more-meta"> 约 1957 字 </span>
          <span class="more-meta"> 预计阅读 4 分钟 </span>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li><a href="#预备知识">预备知识</a></li>
    <li><a href="#初始化项目及运行环境">初始化项目及运行环境</a></li>
    <li><a href="#添加依赖模块">添加依赖模块</a></li>
    <li><a href="#编写代码">编写代码</a>
      <ul>
        <li><a href="#python代码">Python代码</a></li>
        <li><a href="#本地运行">本地运行</a></li>
        <li><a href="#docker配置文件">Docker配置文件</a></li>
      </ul>
    </li>
    <li><a href="#构建和运行docker容器">构建和运行Docker容器</a></li>
    <li><a href="#总结">总结</a></li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p>本文介绍如何快速使用Python, Docker, FastAPI快速开发RESTful API，以及如何编译为Docker镜像，使用Docker容器运行程序。</p>
<!-- raw HTML omitted -->
<h2 id="预备知识">预备知识</h2>
<p>在开始开发之前，需要先安装Python和Docker。</p>
<p>Python是一种流行的编程语言，因此在许多操作系统上都可以很容易地安装。可以使用<a href="https://docs.conda.io/en/latest/miniconda.html">Miniconda</a>，也可以使用官方提供的标准安装包进行安装，个人喜欢Miniconda，不会像<a href="https://www.anaconda.com">Anaconda</a>那么大，同时又提供了非常多必要的依赖模块。</p>
<p>而<a href="https://www.docker.com/">Docker</a>则是一种容器化平台，可帮助我们轻松地将应用程序封装在容器中，便于部署和管理。目前Windows、Linx、macOS对Docker的支持也非常的完善了。</p>
<p><a href="https://fastapi.tiangolo.com/zh/">FastAPI</a> 是一个用于构建 API 的现代、快速（高性能）的 web 框架，使用 Python 3.6+ 并基于标准的 Python 类型提示。</p>
<h2 id="初始化项目及运行环境">初始化项目及运行环境</h2>
<p>Python没有像Java那样极其成熟的一站式的Maven项目管理工具，但是Python有其自身的简洁与规范。像<a href="https://pip.pypa.io/en/stable/reference/build-system/pyproject-toml/">pyproject.toml</a>，以及最近用Rust写的<a href="https://github.com/mitsuhiko/rye">rye</a>，都是很出色的工具。本文使用的例子，完全使用手动管理即可😄</p>
<p>创建一个项目目录my-project，创建文件<code>requirements.txt</code>，<code>main.py</code>，<code>Dockerfile</code>，后面逐一填写里面的内容。</p>
<p>上面我们安装了Miniconda，建议使用conda来创建一个独立的运行环境，这样即不会影响其他项目的运行环境，还可以保持本项目运行环境的整洁。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Shell" data-lang="Shell">conda create -n my-project <span class="nv">python</span><span class="o">=</span>3.9 pip
</code></pre></td></tr></table>
</div>
</div><p>这个命令创建一个名为<code>my-project</code>的运行环境，同时安装3.9版本的Python，和最新的<code>pip</code>工具。</p>
<p>然后激活这个运行环境</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Shell" data-lang="Shell">conda activate my-project
</code></pre></td></tr></table>
</div>
</div><h2 id="添加依赖模块">添加依赖模块</h2>
<p>我们使用<code>requirements.txt</code>来管理程序依赖的模块，<code>requirements.txt</code>文件内容如下</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Shell" data-lang="Shell">-i https://mirrors.aliyun.com/pypi/simple/

fastapi
uvicorn<span class="o">[</span>standard<span class="o">]</span>
</code></pre></td></tr></table>
</div>
</div><p>本文只需要用到这两个模块。第一行的<code>-i</code>指定pip使用阿里pypi镜像地址，如果在国内这会大大加快依赖安装的速度，可以换成阿里或者其他的镜像源。</p>
<p>在本地开发电脑上可以使用下面的命令安装依赖</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Shell" data-lang="Shell">pip install -r requirements.txt
</code></pre></td></tr></table>
</div>
</div><h2 id="编写代码">编写代码</h2>
<h3 id="python代码">Python代码</h3>
<p>FastAPI非常容易使用，也非常适合快速开发RESTful API。以下是我们快速入门的示例代码：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Python" data-lang="Python"><span class="kn">from</span> <span class="nn">fastapi</span> <span class="kn">import</span> <span class="n">FastAPI</span>

<span class="n">app</span> <span class="o">=</span> <span class="n">FastAPI</span><span class="p">()</span>


<span class="nd">@app</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&#34;/&#34;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">read_root</span><span class="p">():</span>
    <span class="k">return</span> <span class="s2">&#34;Hello World&#34;</span>


<span class="nd">@app</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&#34;/items/</span><span class="si">{item_id}</span><span class="s2">&#34;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">read_item</span><span class="p">(</span><span class="n">item_id</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">q</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="kc">None</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">{</span><span class="s2">&#34;item_id&#34;</span><span class="p">:</span> <span class="n">item_id</span><span class="p">,</span> <span class="s2">&#34;q&#34;</span><span class="p">:</span> <span class="n">q</span><span class="p">}</span>

</code></pre></td></tr></table>
</div>
</div><p>在这个简单的示例中，我们创建了一个FastAPI应用程序，它包括两个路由。第一个路由处理根路径并返回一个简单的“Hello World”字符串。第二个路由处理传递给它的路径参数，并返回这些参数的值。第二个路由会以json格式响应内容给调用者（FastAPI框架会自动帮我们字典转换为json数据）。</p>
<h3 id="本地运行">本地运行</h3>
<p>编写完上面的代码，使用命令<code>uvicorn main:app --host 0.0.0.0 --port 8080 --reload</code>启动程序。<code>--reload</code>选项开启了文件更改后自动重启应用。<code>main</code>是模块的名称，冒号后面的<code>app</code>是实例化FastAPI对象的变量名，可以更换成适合应用场景的名称。</p>
<p>FastAPI还有一个贴心的功能是内置了<code>swagger-ui</code>的支持，访问 http://localhost:8080/docs 既可看到所有接口列表，如下图</p>
<p><img src="/img/Python/FastAPI%20Swagger-ui.png" alt="Python FastAPI Docker"></p>
<p>写生产代码的时候，除了单元测试，还可以通过这个界面进行调试与开发，相当的方便。</p>
<h3 id="docker配置文件">Docker配置文件</h3>
<p>先来看看整个目录结构</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Plain" data-lang="Plain">|-- Dockerfile
|-- main.py
`-- requirements.txt
</code></pre></td></tr></table>
</div>
</div><p>上面写的Python代码本文希望放在一个Docker容器来运行，需要编写一个Dockerfile配置文件，进行Docker镜像的编译。将FastAPI应用程序部署到Docker容器中可以方便地处理依赖关系，并且易于部署到各种环境中。以下是如何编写一个简单的Dockerfile：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Shell" data-lang="Shell">FROM python:3.9

WORKDIR /app

RUN <span class="nb">echo</span> “Asia/Shanghai” &gt; /etc/timezone <span class="o">&amp;&amp;</span> cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

COPY requirements.txt /app/

RUN pip3 install -r requirements.txt --no-cache-dir

COPY main.py /app/main.py

EXPOSE <span class="m">8080</span>

CMD <span class="o">[</span><span class="s2">&#34;uvicorn&#34;</span>, <span class="s2">&#34;main:app&#34;</span>, <span class="s2">&#34;--host&#34;</span>, <span class="s2">&#34;0.0.0.0&#34;</span>, <span class="s2">&#34;--port&#34;</span>, <span class="s2">&#34;8080&#34;</span><span class="o">]</span>
</code></pre></td></tr></table>
</div>
</div><ol>
<li>指定使用python 3.9基础镜像</li>
<li>指定容器工作目录为<code>/app</code></li>
<li>设置容器的时区</li>
<li>拷贝<code>requirements.txt</code>到容器</li>
<li>使用<code>requirements.txt</code>安装python依赖，并且不缓存下载的依赖包</li>
<li>拷贝代码到工作目录<code>/app</code></li>
<li>暴露端口到容器外</li>
<li>指定容器启动时的执行命令</li>
</ol>
<h2 id="构建和运行docker容器">构建和运行Docker容器</h2>
<p>在终端窗口中，导航到Dockerfile所在的目录，并输入以下命令以构建Docker镜像：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Shell" data-lang="Shell">docker build -t my_fastapi_app .
</code></pre></td></tr></table>
</div>
</div><p>此命令将构建名为my_fastapi_app的Docker镜像。接下来，您可以使用以下命令运行容器：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Shell" data-lang="Shell">docker run -d --name my_fastapi_container -p 8080:8080 my_fastapi_app
</code></pre></td></tr></table>
</div>
</div><p>此命令将启动Docker容器，并将容器端口8080映射到主机的端口8080。运行后，可以使用<code>http://localhost:8080</code>访问FastAPI应用程序。</p>
<h2 id="总结">总结</h2>
<p>通过以上步骤，我们成功地将FastAPI应用程序部署到了Docker容器中。这种方式使得我们可以轻松地管理应用程序的依赖关系，并且能够在不同的环境中快速部署应用程序。</p>

    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">Kevin Jiang</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2023-06-06
        
    </span>
  </p>
  
  <p class="copyright-item">
    <span class="item-title">许可协议</span>
    <span class="item-content"><a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank">CC BY-NC-ND 4.0</a></span>
  </p>
</div>
<div class="post-reward">
  <input type="checkbox" name="reward" id="reward" hidden />
  <label class="reward-button" for="reward">赞赏支持</label>
  <div class="qr-code">
    
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/wechat_pay_1242x1242.jpg">
        <span>微信打赏</span>
      </label>
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/alipay_600x600.jpg">
        <span>支付宝打赏</span>
      </label>
  </div>
</div><footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/python/">Python</a>
          <a href="/tags/fastapi/">FastAPI</a>
          <a href="/tags/docker/">Docker</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/emacs/%E5%9C%A8spacemacs%E4%B8%AD%E4%BD%BF%E7%94%A8conda%E7%8E%AF%E5%A2%83%E5%90%AF%E7%94%A8lsp-pyright/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">在Spacemacs中使用conda环境启用lsp-pyright</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/python/python%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B%E4%B9%8Bupdate_in_fn/">
            <span class="next-text nav-default">Python函数式编程之 update_in_fn</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:wenlin1988@126.com" class="iconfont icon-email" title="email"></a>
      <a href="https://www.linkedin.com/in/%E6%96%87%E6%9E%97-%E8%92%8B-0a3204126/" class="iconfont icon-linkedin" title="linkedin"></a>
      <a href="https://github.com/kevindragon" class="iconfont icon-github" title="github"></a>
  <a href="http://kevinjiang.info/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 -
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  

  <span class="copyright-year">
    &copy;
    2015 -
    2023<span class="heart"><i class="iconfont icon-heart"></i></span><span>Kevin Jiang</span>
    <a href="https://beian.miit.gov.cn/" target="_blank">湘ICP备2022022745号</a>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c99b103c33d1539acf3025e1913697534542c4a5aa5af0ccc20475ed2863603b.js"></script>
  <script type="text/javascript">
    window.MathJax = {
      tex: {
        inlineMath: [['$','$'], ['\\(','\\)']],
        tags: 'ams',
        }
    };
  </script>
  <script type="text/javascript" async src="/lib/mathjax/es5/tex-mml-chtml.js"></script>

<script id="baidu_analytics">
  var _hmt = _hmt || [];
  (function() {
    if (window.location.hostname === 'localhost') return;
    var hm = document.createElement("script"); hm.async = true;
    hm.src = "https://hm.baidu.com/hm.js?b73ff6d4afc4af9e582d8a5dc068bab9";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>






</body>
</html>
